package com.jrx.anytxn.transaction.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.function.ToBigDecimalFunction;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.CollectorsUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.dto.product.ProductTableRes;
import com.jrx.anytxn.param.dto.system.ChannelTableRes;
import com.jrx.anytxn.param.entity.PrAmortMethod;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.product.IAmortMethodService;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.param.service.system.IChannelTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.DebtBean;
import com.jrx.anytxn.transaction.bean.PaymentLoanInfoBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.common.AccountMainInfoRes;
import com.jrx.anytxn.transaction.dto.common.LoanMainInfoRes;
import com.jrx.anytxn.transaction.dto.loan.LoanInformationRes;
import com.jrx.anytxn.transaction.dto.loan.LoanPlanQueryReq;
import com.jrx.anytxn.transaction.dto.loan.LoanPlanQueryRes;
import com.jrx.anytxn.transaction.dto.loan.PlanRes;
import com.jrx.anytxn.transaction.dto.payment.*;
import com.jrx.anytxn.transaction.entity.*;
import com.jrx.anytxn.transaction.handler.IPaymentHandler;
import com.jrx.anytxn.transaction.handler.impl.LoanHandlerImpl;
import com.jrx.anytxn.transaction.mapper.ext.*;
import com.jrx.anytxn.transaction.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 客户服务订单相关service
 *
 * @author liy
 * date  2019/8/15
 **/
@Service
public class CustomerOrderServiceImpl implements ICustomerOrderService {
    @Resource
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Resource
    private ExtAmRepaymentPlanInfoMapper extAmRepaymentPlanInfoMapper;
    @Resource
    private ExtAmAccountMainInfoMapper extAmAccountMainInfoMapper;
    @Resource
    private ExtTlTransactionInfoMapper extTlTransactionInfoMapper;
    @Resource
    private ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;
    @Autowired
    private IProductTableService productTableService;
    @Autowired
    private IAmortMethodService amortMethodService;
    @Autowired
    private ILoanAccountMainInfoService loanAccountMainInfoService;
    @Autowired
    private IChannelTableService channelTableService;
    @Autowired
    private LoanHandlerImpl loanHandlerImpl;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IPaymentHandler paymentHandler;
    @Resource
    private ExtAmInterestAccrualInfoMapper extAmInterestAccrualInfoMapper;
    @Autowired
    private IDisbursementLogService disbursementLogService;
    @Autowired
    private IRepaymentPlanService repaymentPlanService;
    @Autowired
    private IDebtCalculationService debtCalculationService;
    @Autowired
    private IOrganizationTableService organizationTableService;


    @Override
    public TxnPage<LoanMainInfoRes> getLoanMainWithPage(String channel, String customerId, String tenantId, Integer pageNum, Integer pageSize, String loanId, String loanType, String beginDate, String endDate) {
        AmLoanMainInfo cond = new AmLoanMainInfo();
        cond.setCustomerId(customerId);
        cond.setChannel(channel);
        cond.setTenantId(tenantId);
        cond.setLoanId(loanId);
        cond.setLoanType(loanType);
        Page<AmLoanMainInfo> page = PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(endDate)) {
            Date date=DateUtils.parseDate(endDate);
            endDate=DateUtils.formatDate(DateUtils.add(date,Calendar.HOUR,24));
        }
        List<AmLoanMainInfo> ls = extAmLoanMainInfoMapper.selectByCondSelectivePage(cond,beginDate,endDate);
        List<ChannelTableRes> channelTableResList = channelTableService.findAllChannel(tenantId);

        List<LoanMainInfoRes> res = BeanMapping.copyList(ls, LoanMainInfoRes.class);
        if (!ls.isEmpty()) {
            //获取订单的id集合
            List<String> loanIds = ls.stream().map(AmLoanMainInfo::getLoanId).collect(Collectors.toList());
            //获取产品的
            //根据租户id，客户id，订单号查询 贷款账户表数据
            List<AmLoanAccountInfo> amLoanAccountInfos = extAmLoanAccountInfoMapper.selectByLoanIdsAndTenanIdAndCusId(loanIds, tenantId, customerId);
            //转成订单id为主键的map
            Map<String, AmLoanAccountInfo> loanAccounts = amLoanAccountInfos.stream().collect(Collectors.toMap(AmLoanAccountInfo::getLoanId, Function.identity()));
            // 声明赋值规则
            Consumer<LoanMainInfoRes> consumer = loanMainInfoRes -> {
                //根据订单id获取订单账户
                AmLoanAccountInfo amLoanAccountInfo = loanAccounts.get(loanMainInfoRes.getLoanId());
                //下一还款日期
                loanMainInfoRes.setNextPaymentDate(amLoanAccountInfo.getNextPaymentDate());
                //结清日期
                loanMainInfoRes.setPayoffDate(amLoanAccountInfo.getPayoffDate());
                //账户状态
                loanMainInfoRes.setAccountStatus(amLoanAccountInfo.getAccountStatus());
                loanMainInfoRes.setChannelName(channelTableResList.stream().filter(channelTable -> channelTable.getChannelId().equals(amLoanAccountInfo.getChannel())).findFirst().get().getChineseName());
                //强制催收标识
                loanMainInfoRes.setCompelCollectionFlag(amLoanAccountInfo.getCompelCollectionFlag());
            };
            res.forEach(consumer);
        }
        return new TxnPage(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public TxnRespResult<ArrayList<AmRepaymentPlanRes>> getRepaymentPlan(String customerId, String loanId, String tenantId) {
        TxnRespResult<ArrayList<AmRepaymentPlanRes>> result = new TxnRespResult<>();
        List<AmRepaymentPlanInfo> ls = extAmRepaymentPlanInfoMapper.selectPlanListByCondSelective(customerId, tenantId, loanId);
        List<AmRepaymentPlanRes> res = BeanMapping.copyList(ls, AmRepaymentPlanRes.class);
        //罚息复利交易账户
        Map<Integer, List<AmAccountMainInfo>> accounttMap = null;
        //累计账户map key->期次 value 累计账户list
        Map<Integer, List<AmInterestAccrualInfo>> acctMap = null;
        //获取利息罚息复利交易账户信息
        List<String> accountTypeList = Arrays.asList(TransBizConstant.ACCOUNT_TYPE_04, TransBizConstant.ACCOUNT_TYPE_11, TransBizConstant.ACCOUNT_TYPE_12);
        List<AmAccountMainInfo> accountMainInfoList =
                extAmAccountMainInfoMapper.selectAccounts(loanId, accountTypeList, customerId, tenantId,
                        Arrays.asList(TransBizConstant.ACCOUNT_STATUS_1, TransBizConstant.ACCOUNT_STATUS_2,
                                TransBizConstant.ACCOUNT_STATUS_7, TransBizConstant.ACCOUNT_STATUS_8));
        if (CollectionUtils.isNotEmpty(accountMainInfoList)) {
            accounttMap = accountMainInfoList.stream()
                    .collect(Collectors.groupingBy(AmAccountMainInfo::getBillingTenor));
        }
        //获取累计账户信息
        List<String> typeList = Arrays.asList(TransBizConstant.INTEREST_ACCRUAL_TYPE_66, TransBizConstant.INTEREST_ACCRUAL_TYPE_20, TransBizConstant.INTEREST_ACCRUAL_TYPE_10);
        List<AmInterestAccrualInfo> interestAccrualInfoList =
                extAmInterestAccrualInfoMapper.selectAllAccuAcct(loanId, customerId, tenantId, typeList,
                        Collections.singletonList(TransBizConstant.ACCOUNT_STATUS_1));
        if (CollectionUtils.isNotEmpty(interestAccrualInfoList)) {
            //将累计账户按交易类型分组求欠款之和
            acctMap = interestAccrualInfoList.stream()
                    .collect(Collectors.groupingBy(AmInterestAccrualInfo::getBillingTenor));
        }

        for (AmRepaymentPlanRes info : res) {
            BigDecimal penaltyInterest = BigDecimal.ZERO;
            BigDecimal compoundInterest = BigDecimal.ZERO;
            BigDecimal interest = BigDecimal.ZERO;
            if (acctMap != null && CollectionUtils.isNotEmpty(acctMap.get(info.getBillingTenor()))) {
                Map<String, BigDecimal> bigDecimalMap = acctMap.get(info.getBillingTenor()).stream()
                        .collect(Collectors.groupingBy(AmInterestAccrualInfo::getAccountType,
                                CollectorsUtils.summingBigDecimal(AmInterestAccrualInfo::getAccrualTotalAccruInterest)));
                interest =
                        Optional.ofNullable(bigDecimalMap.get(TransBizConstant.INTEREST_ACCRUAL_TYPE_66)).orElse(BigDecimal.ZERO);//利息
                penaltyInterest =
                        Optional.ofNullable(bigDecimalMap.get(TransBizConstant.INTEREST_ACCRUAL_TYPE_10)).orElse(BigDecimal.ZERO);//罚息
                compoundInterest =
                        Optional.ofNullable(bigDecimalMap.get(TransBizConstant.INTEREST_ACCRUAL_TYPE_20)).orElse(BigDecimal.ZERO);//复利
            }
            if (accounttMap != null && CollectionUtils.isNotEmpty(accounttMap.get(info.getBillingTenor()))) {
                ToBigDecimalFunction<AmAccountMainInfo> toBigDecimalFunction =
                        accountMainInfo -> accountMainInfo.getCurrBalance().subtract(accountMainInfo.getCreditAdjustAmount());
                Map<String, BigDecimal> bigDecimalMap = accounttMap.get(info.getBillingTenor()).stream()
                        .collect(Collectors.groupingBy(AmAccountMainInfo::getAccountType,
                                //CollectorsUtils.summingBigDecimal(toBigDecimalFunction)));
                                CollectorsUtils.summingBigDecimal(AmAccountMainInfo::getCurrBalance)));

                interest =
                        interest.add(Optional.ofNullable(bigDecimalMap.get(TransBizConstant.ACCOUNT_TYPE_04)).orElse(BigDecimal.ZERO));
                penaltyInterest =
                        penaltyInterest.add(Optional.ofNullable(bigDecimalMap.get(TransBizConstant.ACCOUNT_TYPE_11)).orElse(BigDecimal.ZERO));
                compoundInterest =
                        compoundInterest.add(Optional.ofNullable(bigDecimalMap.get(TransBizConstant.ACCOUNT_TYPE_12)).orElse(BigDecimal.ZERO));
            }
            info.setInterestAmount(info.getPlanStatus().equals(TransBizConstant.LOAN_PLAN_STATUS_0) ? info.getInterestAmount() : interest);
            info.setPenaltyInterest(penaltyInterest);
            info.setCompoundInterest(compoundInterest);
        }
        //查询罚息复利累计账户
        return result.getSuccess((ArrayList<AmRepaymentPlanRes>) res);
    }

    @Override
    public TxnPage<AccountMainInfoRes> getAccountMainWithPage(String channel, String customerId, String tenantId, Integer pageNum, Integer pageSize, String accountType, String txnCode, String beginDate, String endDate) {
        AmAccountMainInfo cond = new AmAccountMainInfo();
        cond.setCustomerId(customerId);
        cond.setTenantId(tenantId);
        cond.setChannel(channel);
        cond.setAccountType(accountType);
        cond.setTxnCode(txnCode);
        Page<AmAccountMainInfo> page = PageHelper.startPage(pageNum, pageSize);
        List<AmAccountMainInfo> ls = extAmAccountMainInfoMapper.selectByCondSelectivePage(cond,beginDate,endDate);

        List<AccountMainInfoRes> res = BeanMapping.copyList(ls, AccountMainInfoRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public AccountMainInfoRes getAmLoanMainInfoResByAccountId(String tenantId, String accountId, String customerId) {
        AmAccountMainInfo amAccountMainInfo = extAmAccountMainInfoMapper.selectByAccountId(accountId, tenantId, customerId);
        AccountMainInfoRes accountMainInfoRes = BeanMapping.copy(amAccountMainInfo, AccountMainInfoRes.class);
        return accountMainInfoRes;
    }

    @Override
    public ArrayList<LoanMainInfoRes> getLoanMainInfoByLoanId(String tenantId, String loanId, String customerId, String channel) throws TxnException {
        ArrayList<LoanMainInfoRes> loanMainInfoList = new ArrayList<>();
        AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanId(loanId, customerId, tenantId, channel);
        LoanMainInfoRes loanMainInfoRes = BeanMapping.copy(amLoanMainInfo, LoanMainInfoRes.class);
        //查询产品信息
        ProductTableRes product = productTableService.findByTenIdAndProId(tenantId, amLoanMainInfo.getProductId());
        loanMainInfoRes.setProductName(product.getChineseName());
        //查询还款方式信息
        PrAmortMethod amortMethod = amortMethodService.findByChargerOptionAndId(amLoanMainInfo.getAmortMethodTableId(), amLoanMainInfo.getOrganizationId(), tenantId);
        loanMainInfoRes.setChargeOption(amortMethod.getChargeOption());
        //查询放款流水表
        TlDisbursementLog tlDisbursementLog=disbursementLogService.getTlDisbursementLogByLoanIdAndCusId(tenantId,loanId,customerId);
        if(null !=tlDisbursementLog){
            loanMainInfoRes.setBankName(tlDisbursementLog.getPayeeBankName());
            loanMainInfoRes.setCustomerAccountNumber(tlDisbursementLog.getPayeeAccount());
        }
        //查询贷款账户信息
        AmLoanAccountInfo amLoanAccountInfo = loanAccountMainInfoService.getAmLoanAccountInfoByLoanIdAndCusId(loanId, customerId, tenantId);
        loanMainInfoRes.setPayoffDate(amLoanAccountInfo.getPayoffDate());

        loanMainInfoList.add(loanMainInfoRes);
        return loanMainInfoList;
    }

    @Override
    public TxnPage<TlTransactionInfoRes> getTlTransactionInfoWithPage(String channel, String customerId, String tenantId, Integer pageNum, Integer pageSize, String beginDate, String endDate) {
        Page<TlTransactionInfo> page = PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(endDate)) {
            Date date=DateUtils.parseDate(endDate);
            endDate=DateUtils.formatDate(DateUtils.add(date,Calendar.HOUR,24));
        }
        List<TlTransactionInfo> ls = extTlTransactionInfoMapper.selectByCondSelective(tenantId, channel, customerId, beginDate, endDate);
        List<TlTransactionInfoRes> res = BeanMapping.copyList(ls, TlTransactionInfoRes.class);
        return new TxnPage(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public TlTransactionInfoRes getTlTransactionInfo(String customerId, String tenantId, String channel, String txnNumber) {
        TlTransactionInfo tlTransactionInfo = extTlTransactionInfoMapper.selectTlTransactionInfoByTxnNumber(customerId, tenantId, channel, txnNumber);
        TlTransactionInfoRes tlTransactionInfoRes = BeanMapping.copy(tlTransactionInfo, TlTransactionInfoRes.class);
        return tlTransactionInfoRes;
    }

    @Override
    public AmRepaymentPlanRes getOrderPlanByTenor(String customerId, String tenantId, String channel, String loanId, Integer billingTenor) {
        AmRepaymentPlanInfo amRepaymentPlanInf = extAmRepaymentPlanInfoMapper.selectByLoanIdAndTenor(customerId, tenantId, channel, loanId, billingTenor);
        AmRepaymentPlanRes amRepaymentPlanRes = BeanMapping.copy(amRepaymentPlanInf, AmRepaymentPlanRes.class);
        return amRepaymentPlanRes;
    }

    @Override
    public TxnRespResult<ShowHandlePaymentRes> showHandlePayment(String customerId, String loanId, String tenantId, String channel) throws TxnException {
        TxnRespResult<ShowHandlePaymentRes> result = new TxnRespResult<>();
        CmCustomerSecondLevel cmCustomerSecondLevel = customerService.getSecondByChannelAndCustomerIdAndTensnId(channel, customerId, tenantId, null);
        LoanPlanQueryReq loanQueryReq = new LoanPlanQueryReq();
        loanQueryReq.setLoanId(loanId);
        loanQueryReq.setTenantId(tenantId);
        loanQueryReq.setChannel(channel);
        loanQueryReq.setUserId(cmCustomerSecondLevel.getUserId());
        LoanPlanQueryRes queryRes = loanHandlerImpl.loanPlanHandle(loanQueryReq);
        ShowHandlePaymentRes res = new ShowHandlePaymentRes();
        res.setLoanId(queryRes.getLoanId());
        res.setChannel(channel);
        res.setCustomerId(customerId);
        BigDecimal totalAmt = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(PlanRes::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal principalAmount = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(PlanRes::getPrincipalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal interestAmount = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(PlanRes::getInterestAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal penaltyInterest = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(plan -> plan.getPayablePenaltyInterest().subtract(plan.getPaymentPenaltyInterest())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal compoundInterest = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(plan -> plan.getPayableCompoundInterest().subtract(plan.getPaymentCompoundInterest())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal feeAmount = queryRes.getPlanList().stream().filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPaymentFlag()) || TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPaymentFlag()))
                .map(PlanRes::getFeeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        res.setTotalAmount(totalAmt);
        res.setPrincipalAmount(principalAmount);
        res.setInterestAmount(interestAmount);
        res.setPenaltyInterest(penaltyInterest);
        res.setCompoundInterest(compoundInterest);
        res.setFeeAmount(feeAmount);
        return result.getSuccess(res);
    }

    @Override
    public TxnRespResult<ShowHandlePaymentRes> trailHandlePayment(String customerId, String loanId, String tenantId, String channel, String paymentMethod, String repayAmount, String principalAmt) throws TxnException {
        TxnRespResult<ShowHandlePaymentRes> result = new TxnRespResult<>();
        ShowHandlePaymentRes showHandlePaymentRes = new ShowHandlePaymentRes();
        showHandlePaymentRes.setLoanId(loanId);
        showHandlePaymentRes.setChannel(channel);
        showHandlePaymentRes.setCustomerId(customerId);
        CmCustomerSecondLevel cmCustomerSecondLevel = customerService.getSecondByChannelAndCustomerIdAndTensnId(channel, customerId, tenantId, null);
        List<PaymentLoanInfoBean> loanList = new ArrayList();
        PaymentLoanInfoBean bean = new PaymentLoanInfoBean();
        bean.setLoanId(loanId);
        loanList.add(bean);
        if (TransBizConstant.REPAYMENT_TYPE_PREPAY.equals(paymentMethod)) {
            PrePayTrialReq prePayTrialReq = new PrePayTrialReq();
            prePayTrialReq.setPrincipalAmount(new BigDecimal(repayAmount));
            prePayTrialReq.setLoanId(loanId);
            prePayTrialReq.setChannel(channel);
            prePayTrialReq.setTenantId(tenantId);
            prePayTrialReq.setUserId(cmCustomerSecondLevel.getUserId());
            PrePayTrialRes res = paymentHandler.prePayTrail(prePayTrialReq);
            showHandlePaymentRes.setTotalAmount(res.getTotalAmount());
            showHandlePaymentRes.setPrincipalAmount(res.getPrincipalAmount());
            showHandlePaymentRes.setInterestAmount(res.getInterestAmount());
            showHandlePaymentRes.setPenaltyInterest(res.getPenaltyAmount());
            showHandlePaymentRes.setFeeAmount(res.getFeeAmount());
            showHandlePaymentRes.setCompoundInterest(res.getCompountAmount());
            showHandlePaymentRes.setPayFeeAmount(res.getPreFeeAmount());
        }
        if (TransBizConstant.REPAYMENT_TYPE_PRETERMINTION.equals(paymentMethod)) {
            PaymentTrialReq paymentTrialReq = new PaymentTrialReq();
            paymentTrialReq.setLoanList(loanList);
            paymentTrialReq.setChannel(channel);
            paymentTrialReq.setTenantId(tenantId);
            paymentTrialReq.setUserId(cmCustomerSecondLevel.getUserId());
            AdvanceSettleTrialRes res = paymentHandler.preterminationTrail(paymentTrialReq);
            showHandlePaymentRes.setTotalAmount(res.getTotalAmount());
            showHandlePaymentRes.setPrincipalAmount(res.getLoanList().get(0).getPrincipalAmount());
            showHandlePaymentRes.setInterestAmount(res.getLoanList().get(0).getInterestAmount());
            showHandlePaymentRes.setPenaltyInterest(res.getLoanList().get(0).getPenaltyAmount());
            showHandlePaymentRes.setFeeAmount(res.getLoanList().get(0).getFeeAmount());
            showHandlePaymentRes.setCompoundInterest(res.getLoanList().get(0).getCompountAmount());
            showHandlePaymentRes.setPayFeeAmount(res.getLoanList().get(0).getPreFeeAmount());

        } else if (TransBizConstant.REPAYMENT_TYPE_OVERDUE.equals(paymentMethod)) {
            DelinquencyTrialReq paymentTrialReq = new DelinquencyTrialReq();
            paymentTrialReq.setLoanList(loanList);
            paymentTrialReq.setChannel(channel);
            paymentTrialReq.setTenantId(tenantId);
            paymentTrialReq.setUserId(cmCustomerSecondLevel.getUserId());
            DelinquencyTrialRes res = paymentHandler.overdueTrail(paymentTrialReq);
            showHandlePaymentRes.setTotalAmount(res.getTotalAmount());

            BigDecimal principalAmount = res.getLoanList().get(0).getPlanList().stream().map(DebtDetailRes::getPrincipalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal interestAmount = res.getLoanList().get(0).getPlanList().stream().map(DebtDetailRes::getInterestAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal penaltyInterest = res.getLoanList().get(0).getPlanList().stream().map(DebtDetailRes::getPenaltyAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal compoundInterest = res.getLoanList().get(0).getPlanList().stream().map(DebtDetailRes::getCompountAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal feeAmount = res.getLoanList().get(0).getPlanList().stream().map(DebtDetailRes::getFeeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            showHandlePaymentRes.setPrincipalAmount(principalAmount);
            showHandlePaymentRes.setInterestAmount(interestAmount);
            showHandlePaymentRes.setPenaltyInterest(penaltyInterest);
            showHandlePaymentRes.setCompoundInterest(compoundInterest);
            showHandlePaymentRes.setFeeAmount(feeAmount);


        } else if (TransBizConstant.REPAYMENT_TYPE_PAY.equals(paymentMethod)) {
            OnDuePayTrialReq onDuePayTrialReq = new OnDuePayTrialReq();
            onDuePayTrialReq.setLoanList(loanList);
            onDuePayTrialReq.setChannel(channel);
            onDuePayTrialReq.setTenantId(tenantId);
            onDuePayTrialReq.setUserId(cmCustomerSecondLevel.getUserId());
            OnDuePayTrialRes res = paymentHandler.onDuePayTrial(onDuePayTrialReq);
            showHandlePaymentRes.setTotalAmount(res.getTotalAmount());
            showHandlePaymentRes.setPrincipalAmount(res.getLoanList().get(0).getPrincipalAmount());
            showHandlePaymentRes.setInterestAmount(res.getLoanList().get(0).getInterestAmount());
            showHandlePaymentRes.setPenaltyInterest(res.getLoanList().get(0).getPenaltyAmount());
            showHandlePaymentRes.setFeeAmount(res.getLoanList().get(0).getFeeAmount());
            showHandlePaymentRes.setCompoundInterest(res.getLoanList().get(0).getCompountAmount());

        }else if (TransBizConstant.REPAYMENT_TYPE_REFUND.equals(paymentMethod)) {
            OnDuePayTrialReq onDuePayTrialReq = new OnDuePayTrialReq();
            onDuePayTrialReq.setLoanList(loanList);
            onDuePayTrialReq.setChannel(channel);
            onDuePayTrialReq.setTenantId(tenantId);
            onDuePayTrialReq.setUserId(cmCustomerSecondLevel.getUserId());
            showHandlePaymentRes.setTotalAmount(new BigDecimal(principalAmt));
            showHandlePaymentRes.setPrincipalAmount(new BigDecimal(principalAmt));
            showHandlePaymentRes.setInterestAmount(BigDecimal.ZERO);
            showHandlePaymentRes.setPenaltyInterest(BigDecimal.ZERO);
            showHandlePaymentRes.setFeeAmount(BigDecimal.ZERO);
            showHandlePaymentRes.setCompoundInterest(BigDecimal.ZERO);
        }
        result.getSuccess(showHandlePaymentRes);
        return result;
    }

    @Override
    public ArrayList<LoanInformationRes> getLoanInformation(String channel, String customerId, String tenantId) throws TxnBizException {
        List<AmLoanAccountInfo> amLoanAccountInfoList = extAmLoanAccountInfoMapper.selectByCustAndChannelAndStatus(customerId,channel,tenantId,
                Arrays.asList(TransBizConstant.ACCOUNT_STATUS_1,TransBizConstant.ACCOUNT_STATUS_2));

        ArrayList<LoanInformationRes> loanList = new ArrayList<>();
        LoanInformationRes res = new LoanInformationRes();

        if(CollectionUtils.isEmpty(amLoanAccountInfoList)){
            loanList.add(res);
            return loanList;
        }

        PrOrganizationTable organization =
                organizationTableService.findByOrId(amLoanAccountInfoList.get(0).getOrganizationId(), tenantId);
        Date bussinessDate = organization.getNextProcessingDate();

        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal principalAmount = BigDecimal.ZERO;
        BigDecimal interestAmount = BigDecimal.ZERO;
        BigDecimal penaltyAmount = BigDecimal.ZERO;
        BigDecimal compountAmount = BigDecimal.ZERO;

        for(AmLoanAccountInfo amLoanAccountInfo : amLoanAccountInfoList){
            //获取订单未抛、正常、逾期状态的还款计划
            List<AmRepaymentPlanInfo> repaymentPlanInfos = repaymentPlanService.getPlanList(amLoanAccountInfo.getLoanId(),
                    amLoanAccountInfo.getCustomerId(), amLoanAccountInfo.getTenantId(), null)
                    .stream()
                    .filter(x -> Arrays.asList(TransBizConstant.LOAN_PLAN_STATUS_0, TransBizConstant.LOAN_PLAN_STATUS_1,
                            TransBizConstant.LOAN_PLAN_STATUS_2).contains(x.getPlanStatus()))
                    .collect(Collectors.toList());
            DebtBean debtBean = debtCalculationService.getBalance(amLoanAccountInfo, repaymentPlanInfos, bussinessDate, null, null, null, false);

            totalAmount = totalAmount.add(debtBean.getTotalAmount());
            principalAmount = principalAmount.add(debtBean.getPrincipalAmount());
            interestAmount = interestAmount.add(debtBean.getInterestAmount());
            penaltyAmount = penaltyAmount.add(debtBean.getPenaltyAmount());
            compountAmount = compountAmount.add(debtBean.getCompountAmount());
        }
        res.setTotalAmount(totalAmount);
        res.setTotaNumber(amLoanAccountInfoList.size());
        res.setPrincipalAmount(principalAmount);
        res.setInterestAmount(interestAmount);
        res.setPenaltyAmount(penaltyAmount);
        res.setCompountAmount(compountAmount);
        res.setChannel(channel);
        res.setCustomerId(customerId);
        res.setTenantId(tenantId);
        loanList.add(res);
        return loanList;
    }

    @Override
    public ArrayList<LoanInformationRes> getLoanInformationByLoanId(String loanId, String customerId, String tenantId) throws TxnBizException {
        AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanIdAndAccountStatus(loanId,customerId,tenantId,
                Arrays.asList(TransBizConstant.ACCOUNT_STATUS_1,TransBizConstant.ACCOUNT_STATUS_2,TransBizConstant.ACCOUNT_STATUS_6));
        LoanInformationRes res = new LoanInformationRes();
        ArrayList<LoanInformationRes> loanList = new ArrayList<>();

        if(null == amLoanAccountInfo){
            loanList.add(res);
            return loanList;
        }

        PrOrganizationTable organization =
                organizationTableService.findByOrId(amLoanAccountInfo.getOrganizationId(), tenantId);
        Date bussinessDate = organization.getNextProcessingDate();

        //获取订单未抛、正常、逾期状态的还款计划
        List<AmRepaymentPlanInfo> repaymentPlanInfos = repaymentPlanService.getPlanList(amLoanAccountInfo.getLoanId(),
                amLoanAccountInfo.getCustomerId(), amLoanAccountInfo.getTenantId(),
                Arrays.asList(TransBizConstant.LOAN_PLAN_STATUS_0, TransBizConstant.LOAN_PLAN_STATUS_1,
                        TransBizConstant.LOAN_PLAN_STATUS_2));

        DebtBean debtBean = debtCalculationService.getBalance(amLoanAccountInfo, repaymentPlanInfos, bussinessDate, null, null, null, false);

        res.setPrincipalAmount(debtBean.getPrincipalAmount());
        res.setInterestAmount(debtBean.getInterestAmount());
        res.setPenaltyAmount(debtBean.getPenaltyAmount());
        res.setCompountAmount(debtBean.getCompountAmount());

        loanList.add(res);
        return loanList;
    }


}
